﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Infragistics.Win;
using Infragistics.Win.UltraWinGrid;
using Infragistics.Excel;
namespace BYManageInfoSystem
{
    public partial class Frm_MonthDepRecvMoneyInvoiceDetailAndReg : Form
    {
        private DGBY.BLL.FacFeeTab m_bllFacFeeTab = new DGBY.BLL.FacFeeTab();
        private DGBY.BLL.BYDepartTab m_bllBYDepartTab = new DGBY.BLL.BYDepartTab();
        private DGBY.BLL.FeeTab m_bllFeeTab = new DGBY.BLL.FeeTab();
        private DGBY.BLL.CargoBoxTab m_bllCargoBoxTab = new DGBY.BLL.CargoBoxTab();
        private DGBY.BLL.FacFeeRelationTab m_bllFacFeeRelationTab = new DGBY.BLL.FacFeeRelationTab();
        private Dictionary<string, DataRow> dicContractNo2DataRow = new Dictionary<string, DataRow>();
        private DGBY.BLL.FeeInvoiceTab m_bllFeeInvoiceTab = new DGBY.BLL.FeeInvoiceTab();
        private int m_nSelectFeeTTLoanTabID = 0;
        public class CustomMergedCellEvaluator : Infragistics.Win.UltraWinGrid.IMergedCellEvaluator
        {
            UltraGridColumn m_BaseColumn = null;
            public CustomMergedCellEvaluator(UltraGrid UltraGridTemp)
            {
                foreach (UltraGridColumn column2 in UltraGridTemp.DisplayLayout.Bands[0].Columns)
                {
                    string str = column2.Header.Caption;
                    if (str == "工厂简称")
                    {
                        m_BaseColumn = column2;
                        break;
                    }
                }
            }
            // 合并日期相同的单元格（无需时间精确相同）
            public bool ShouldCellsBeMerged(UltraGridRow row1, UltraGridRow row2, UltraGridColumn column)
            {
                string str1 = (string)row1.GetCellValue(m_BaseColumn);
                string str2 = (string)row2.GetCellValue(m_BaseColumn);

                return str1 == str2;

            }

        }


        public Frm_MonthDepRecvMoneyInvoiceDetailAndReg()
        {
            InitializeComponent();
        }
        public void LocalPrintPreveiw()
        {
            Infragistics.Shared.ResourceCustomizer rc = Infragistics.Win.Printing.Resources.Customizer;//Resources.Customizer;
            rc.SetCustomizedString("PrintPreview_DialogCaption", "打印预览");
            rc.SetCustomizedString("PrintPreview_Tool_Print", "打印(&P)");
            rc.SetCustomizedString("PrintPreview_Tool_ClosePreview", "关闭(&C)");
            rc.SetCustomizedString("PrintPreview_Tool_ContextMenuPreviewZoom", "显示比例");
            rc.SetCustomizedString("PrintPreview_Tool_Current_Page", "当前页");
            rc.SetCustomizedString("PrintPreview_Tool_Exit", "退出(&X)");
            rc.SetCustomizedString("PrintPreview_Tool_First_Page", "第一页");
            rc.SetCustomizedString("PrintPreview_Tool_Go_To", "跳至");
            rc.SetCustomizedString("PrintPreview_Tool_Last_Page", "最后一页");
            rc.SetCustomizedString("PrintPreview_Tool_Next_Page", "下一页");
            rc.SetCustomizedString("PrintPreview_Tool_Previous_Page", "前一页");
            rc.SetCustomizedString("PrintPreview_Tool_Next_View", "下一视图(&N)");
            rc.SetCustomizedString("PrintPreview_Tool_Previous_View", "前一视图(&P)");
            rc.SetCustomizedString("PrintPreview_Tool_Hand_Tool", "手型工具(&H)");
            rc.SetCustomizedString("PrintPreview_Tool_Page_Setup", "页面设置(&U)");
            rc.SetCustomizedString("PrintPreview_Tool_Snapshot_Tool", "快照工具(&S)");
            rc.SetCustomizedString("PrintPreview_Tool_View", "视图(&V)");
            rc.SetCustomizedString("PrintPreview_Tool_Whole_Page", "合适页");
            rc.SetCustomizedString("PrintPreview_Tool_Zoom", "缩放(&Z)");
            rc.SetCustomizedString("PrintPreview_Tool_Zoom_In", "放大");

            rc.SetCustomizedString("PrintPreview_Tool_Zoom_Out", "缩小");

            rc.SetCustomizedString("PrintPreview_ToolCategory_Context_Menus", "上下文菜单");
            rc.SetCustomizedString("PrintPreview_ToolCategory_File", "文件");
            rc.SetCustomizedString("PrintPreview_ToolCategory_Menus", "菜单");
            rc.SetCustomizedString("PrintPreview_ToolCategory_Tools", "工具栏");
            rc.SetCustomizedString("PrintPreview_ToolCategory_View", "视图");
            rc.SetCustomizedString("PrintPreview_ToolCategory_Zoom_Mode", "缩放模式");

            rc.SetCustomizedString("PrintPreview_ToolTip_ClosePreview", "关闭");
            rc.SetCustomizedString("PrintPreview_ToolTip_Zoom", "缩放");
            rc.SetCustomizedString("StatusBar_Page_X_OF_X", "页:{0}/{1}");

            rc.SetCustomizedString("CustomizeImg_ToolBar_MenuBar", "菜单");
            rc.SetCustomizedString("CustomizeImg_ToolBar_Standard", "标准");
            rc.SetCustomizedString("CustomizeImg_ToolBar_View", "视图");
            rc.SetCustomizedString("PrintPreview_Tool_File", "文件(&F)");
            rc.SetCustomizedString("PrintPreview_Tool_Tools", "工具(&T)");
            rc.SetCustomizedString("PrintPreview_Tool_Dynamic_Zoom_Tool", "动态缩放工具(&D)");
            rc.SetCustomizedString("PrintPreview_Tool_Zoom_Out_Tool", "缩小工具");
            rc.SetCustomizedString("PrintPreview_Tool_Zoom_In_Tool", "放大工具");
            // rc.SetCustomizedString("PrintPreview_Tool_Page_Layout","菜单");
            rc.SetCustomizedString("PreviewRowColSelection_Cancel", "取消");
            rc.SetCustomizedString("PreviewRowColSelection_SelectedPages", "{0} x {1} 页");

            rc.SetCustomizedString("PreviewRowColSelection_Cancel", "取消");
            rc.SetCustomizedString("PrintPreview_Tool_Page_Width", "页宽");
            rc.SetCustomizedString("PrintPreview_ZoomListItem_MarginWidth", "文字宽度");
            rc.SetCustomizedString("PrintPreview_ZoomListItem_PageWidth", "页宽");
            rc.SetCustomizedString("PrintPreview_ZoomListItem_WholePage", "合适页");
            rc.SetCustomizedString("PrintPreview_Tool_Page_Layout", "页面布局");
            rc.SetCustomizedString("PrintPreview_Tool_Margin_Width", "文字宽度");
            rc.SetCustomizedString("ContextMenuPreviewHand", "缩放视图");


            rc.SetCustomizedString("PrintPreview_Tool_Reduce_Page_Thumbnails", "缩小");
            rc.SetCustomizedString("PrintPreview_Tool_Show_Page_Numbers", "显示页号");
            rc.SetCustomizedString("PrintPreview_Tool_ContextMenuThumbnail", "缩略图");
            rc.SetCustomizedString("PrintPreview_Tool_Enlarge_Page_Thumbnails", "放大");
            rc.SetCustomizedString("PrintPreview_Tool_Thumbnails", "缩略图");
            rc.SetCustomizedString("PrintPreview_Tool_Continuous", "连续排序");
            //说明
            rc.SetCustomizedString("StatusBar_DynamicZoom_Instructions", "单击并拖动进行缩放操作");
            rc.SetCustomizedString("StatusBar_Page_X_OF_X", "当前页: {0} / {1}");
            rc.SetCustomizedString("StatusBar_SnapShot_Instructions", "单击并拖动,系统将选定矩型区域复制到剪帖板");
            rc.SetCustomizedString("StatusBar_ZoomIn_Instructions", "单击并拖动,系统将放大选定矩型区域");
            rc.SetCustomizedString("StatusBar_ZoomOut_Instructions", "单击并拖动,系统将缩小选定矩型区域");
            rc.SetCustomizedString("StatusBar_Hand_Instructions", "单击并拖动以便显示更多内容");
        }
        private void InitCombox()
        {
            DataSet ds = m_bllBYDepartTab.GetList("");
            if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                this.comboBoxDep.DataSource = ds.Tables[0];
                this.comboBoxDep.DisplayMember = "部门名称";
                this.comboBoxDep.ValueMember = "BYDepartTabID";
                this.comboBoxDep.SelectedIndex = 0;
            }
        }
        /// 取得某月的第一天
        /// </summary>
        /// <param name="datetime">要取得月份第一天的时间</param>
        /// <returns></returns>
        private DateTime FirstDayOfMonth(DateTime datetime)
        {
            return datetime.AddDays(1 - datetime.Day);
        }
        /// <summary>
        /// 取得某月的最后一天
        /// </summary>
        /// <param name="datetime">要取得月份最后一天的时间</param>
        /// <returns></returns>
        private DateTime LastDayOfMonth(DateTime datetime)
        {
            return datetime.AddDays(1 - datetime.Day).AddMonths(1).AddDays(-1);
        }
        private void MakeColumn(DataTable dt)
        {
            dt.Columns.Add("工厂简称", System.Type.GetType("System.String"));
            dt.Columns.Add("订单号", System.Type.GetType("System.String"));
            dt.Columns.Add("合同号", System.Type.GetType("System.String"));
            dt.Columns.Add("柜号", System.Type.GetType("System.String"));
            dt.Columns.Add("柜数", System.Type.GetType("System.Int32"));

            dt.Columns.Add("百业收据", System.Type.GetType("System.Decimal"));
            dt.Columns.Add("百业装卸发票", System.Type.GetType("System.Decimal"));
            dt.Columns.Add("运输发票", System.Type.GetType("System.Decimal"));
            dt.Columns.Add("应收费用合计", System.Type.GetType("System.Decimal"));
            dt.Columns.Add("应付费用", System.Type.GetType("System.Decimal"));

            dt.Columns.Add("商检金额", System.Type.GetType("System.Decimal"));
            dt.Columns.Add("应付商检费", System.Type.GetType("System.Decimal"));
            dt.Columns.Add("应收商检费", System.Type.GetType("System.Decimal"));

            DataSet ds = m_bllFeeTab.GetFeeNameList("FeeCateTab.FeeCateName like " + "'%" + "商检" + "%'");
            if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    string strTemp = ds.Tables[0].Rows[i]["FeeName"].ToString();
                    dt.Columns.Add(strTemp, System.Type.GetType("System.Decimal"));
                }
            }

            dt.Columns.Add("应收商检费合计", System.Type.GetType("System.Decimal"));


            dt.Columns.Add("运输公司", System.Type.GetType("System.String"));
            dt.Columns.Add("应付运输费", System.Type.GetType("System.Decimal"));
            ds = m_bllFeeTab.GetFeeNameList("FeeCateTab.FeeCateName like " + "'%" + "运输" + "%'");
            if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    string strTemp = ds.Tables[0].Rows[i]["FeeName"].ToString();
                    dt.Columns.Add(strTemp, System.Type.GetType("System.Decimal"));
                }
            }
            dt.Columns.Add("应收运输费合计", System.Type.GetType("System.Decimal"));


            dt.Columns.Add("报关行", System.Type.GetType("System.String"));
            dt.Columns.Add("报关单号", System.Type.GetType("System.String"));
            dt.Columns.Add("核销单号", System.Type.GetType("System.String"));
            dt.Columns.Add("报关金额", System.Type.GetType("System.Decimal"));
            dt.Columns.Add("币种", System.Type.GetType("System.String"));
            dt.Columns.Add("经营单位", System.Type.GetType("System.String"));
            dt.Columns.Add("申报日期", System.Type.GetType("System.DateTime"));
            dt.Columns.Add("应付报关费", System.Type.GetType("System.Decimal"));

            ds = m_bllFeeTab.GetFeeNameList("FeeCateTab.FeeCateName like " + "'%" + "报关" + "%'");
            if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    string strTemp = ds.Tables[0].Rows[i]["FeeName"].ToString();
                    dt.Columns.Add(strTemp, System.Type.GetType("System.Decimal"));
                }
            }
            dt.Columns.Add("应收报关费合计", System.Type.GetType("System.Decimal"));

            dt.Columns.Add("公帐汇款船务费", System.Type.GetType("System.Decimal"));
            dt.Columns.Add("私帐汇款船务费", System.Type.GetType("System.Decimal"));

            ds = m_bllFeeTab.GetFeeNameList("FeeCateTab.FeeCateName like " + "'%" + "单证" + "%'");
            if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    string strTemp = ds.Tables[0].Rows[i]["FeeName"].ToString();
                    dt.Columns.Add(strTemp, System.Type.GetType("System.Decimal"));
                }
            }

            dt.Columns.Add("应收单证费用合计", System.Type.GetType("System.Decimal"));
            dt.Columns.Add("应付单证费用合计", System.Type.GetType("System.Decimal"));

            ds = m_bllFeeTab.GetFeeNameList("FeeCateTab.FeeCateName like " + "'%" + "其他" + "%'");
            if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    string strTemp = ds.Tables[0].Rows[i]["FeeName"].ToString();
                    dt.Columns.Add(strTemp, System.Type.GetType("System.Decimal"));
                }
            }

            dt.Columns.Add("应收其他费用合计", System.Type.GetType("System.Decimal"));
            dt.Columns.Add("应付其他费用合计", System.Type.GetType("System.Decimal"));
        }
        private void FillDataTable(DataTable dtNew, DataSet ds)
        {
            if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    DataRow dr = dtNew.NewRow();
                    int nBGDComeBackTabID = Convert.ToInt32(ds.Tables[0].Rows[i]["BGDComeBackTabID"].ToString(), 10);
                    DataSet ds2 = m_bllCargoBoxTab.GetAllCargoBoxInfo("CargoBoxTab.BGDComeBackTabID = " + nBGDComeBackTabID.ToString());
                    if (ds2.Tables.Count > 0 && ds2.Tables[0].Rows.Count > 0)
                    {
                        dr["柜数"] = ds2.Tables[0].Rows.Count;
                        StringBuilder strSql = new StringBuilder();
                        for (int j = 0; j < ds2.Tables[0].Rows.Count; j++)
                        {
                            strSql.Append(ds2.Tables[0].Rows[j]["集装箱号"].ToString());
                            strSql.Append("\n");
                        }
                        dr["柜号"] = strSql.ToString();
                    }
                    else
                    {
                        dr["柜数"] = 0;
                        dr["柜号"] = "";
                    }


                    dr["合同号"] = ds.Tables[0].Rows[i]["合同编号"];
                    dr["商检金额"] = ds.Tables[0].Rows[i]["商检金额"];
                    dr["应付商检费"] = ds.Tables[0].Rows[i]["应付商检金额"];
                    dr["应收商检费"] = ds.Tables[0].Rows[i]["应收商检金额"];

                    dr["经营单位"] = ds.Tables[0].Rows[i]["经营单位"];
                    dr["订单号"] = ds.Tables[0].Rows[i]["订单号"];
                    dr["工厂简称"] = ds.Tables[0].Rows[i]["工厂名称"];
                    dr["报关行"] = ds.Tables[0].Rows[i]["报关行名称"];
                    dr["报关单号"] = ds.Tables[0].Rows[i]["报关单号"];
                    dr["核销单号"] = ds.Tables[0].Rows[i]["核销单号"];
                    dr["币种"] = ds.Tables[0].Rows[i]["币种"];
                    dr["申报日期"] = ds.Tables[0].Rows[i]["申报日期"];

                    dr["报关金额"] = ds.Tables[0].Rows[i]["报关金额"];
                    dr["运输公司"] = ds.Tables[0].Rows[i]["运输公司"];
                    dr["经营单位"] = ds.Tables[0].Rows[i]["单证公司"];
                    dr["公帐汇款船务费"] = ds.Tables[0].Rows[i]["公帐汇款船务费"];
                    dr["私帐汇款船务费"] = ds.Tables[0].Rows[i]["私帐汇款船务费"];
                    dr["运输公司"] = ds.Tables[0].Rows[i]["运输公司"];
                    dr["应付运输费"] = ds.Tables[0].Rows[i]["应付运输费"];

                    dr["应付报关费"] = ds.Tables[0].Rows[i]["应付报关费"];
                    dr["应付单证费用合计"] = ds.Tables[0].Rows[i]["应付单证费"];
                    dr["应付其他费用合计"] = ds.Tables[0].Rows[i]["应付其他费"];

                    int nSelectFacFeeTabID = Convert.ToInt32(ds.Tables[0].Rows[i]["FacFeeTabID"].ToString(), 10);
                    DataSet ds3 = m_bllFacFeeRelationTab.GetFeeNameList("FacFeeTabID = " + nSelectFacFeeTabID.ToString() + " and FeeCateTab.FeeCateName like " + "'%" + "商检" + "%'");

                    if (ds3.Tables.Count > 0 && ds3.Tables[0].Rows.Count > 0)
                    {
                        Decimal dtTotalTemp = 0;
                        for (int k = 0; k < ds3.Tables[0].Rows.Count; k++)
                        {
                            string strTemp = ds3.Tables[0].Rows[k]["费用名称"].ToString();
                            dr[strTemp] = ds3.Tables[0].Rows[k]["费用金额"].ToString();
                            dtTotalTemp += Convert.ToDecimal(ds3.Tables[0].Rows[k]["费用金额"].ToString());

                        }

                        dr["应收商检费合计"] = (Decimal)dr["应收商检费"] + dtTotalTemp;
                    }

                    ds3 = m_bllFacFeeRelationTab.GetFeeNameList("FacFeeTabID = " + nSelectFacFeeTabID.ToString() + " and FeeCateTab.FeeCateName like " + "'%" + "运输" + "%'");

                    if (ds3.Tables.Count > 0 && ds3.Tables[0].Rows.Count > 0)
                    {
                        Decimal dtTotalTemp = 0;
                        for (int k = 0; k < ds3.Tables[0].Rows.Count; k++)
                        {
                            string strTemp = ds3.Tables[0].Rows[k]["费用名称"].ToString();
                            dr[strTemp] = ds3.Tables[0].Rows[k]["费用金额"].ToString();
                            dtTotalTemp += Convert.ToDecimal(ds3.Tables[0].Rows[k]["费用金额"].ToString());

                        }

                        dr["应收运输费合计"] = dtTotalTemp;
                    }

                    ds3 = m_bllFacFeeRelationTab.GetFeeNameList("FacFeeTabID = " + nSelectFacFeeTabID.ToString() + " and FeeCateTab.FeeCateName like " + "'%" + "报关" + "%'");

                    if (ds3.Tables.Count > 0 && ds3.Tables[0].Rows.Count > 0)
                    {
                        Decimal dtTotalTemp = 0;
                        for (int k = 0; k < ds3.Tables[0].Rows.Count; k++)
                        {
                            string strTemp = ds3.Tables[0].Rows[k]["费用名称"].ToString();
                            dr[strTemp] = ds3.Tables[0].Rows[k]["费用金额"].ToString();
                            dtTotalTemp += Convert.ToDecimal(ds3.Tables[0].Rows[k]["费用金额"].ToString());

                        }

                        dr["应收报关费合计"] = dtTotalTemp;
                    }
                    ds3 = m_bllFacFeeRelationTab.GetFeeNameList("FacFeeTabID = " + nSelectFacFeeTabID.ToString() + " and FeeCateTab.FeeCateName like " + "'%" + "单证" + "%'");

                    if (ds3.Tables.Count > 0 && ds3.Tables[0].Rows.Count > 0)
                    {
                        Decimal dtTotalTemp = 0;
                        for (int k = 0; k < ds3.Tables[0].Rows.Count; k++)
                        {
                            string strTemp = ds3.Tables[0].Rows[k]["费用名称"].ToString();
                            dr[strTemp] = ds3.Tables[0].Rows[k]["费用金额"].ToString();
                            dtTotalTemp += Convert.ToDecimal(ds3.Tables[0].Rows[k]["费用金额"].ToString());

                        }

                        dr["应收单证费用合计"] = dtTotalTemp;
                    }

                    ds3 = m_bllFacFeeRelationTab.GetFeeNameList("FacFeeTabID = " + nSelectFacFeeTabID.ToString() + " and FeeCateTab.FeeCateName like " + "'%" + "其他" + "%'");

                    if (ds3.Tables.Count > 0 && ds3.Tables[0].Rows.Count > 0)
                    {
                        Decimal dtTotalTemp = 0;
                        for (int k = 0; k < ds3.Tables[0].Rows.Count; k++)
                        {
                            string strTemp = ds3.Tables[0].Rows[k]["费用名称"].ToString();
                            dr[strTemp] = ds3.Tables[0].Rows[k]["费用金额"].ToString();
                            dtTotalTemp += Convert.ToDecimal(ds3.Tables[0].Rows[k]["费用金额"].ToString());

                        }

                        dr["应收其他费用合计"] = dtTotalTemp;
                    }

                    dr["百业收据"] = (Decimal)dr["应收单证费用合计"] + (Decimal)dr["应收其他费用合计"] + (Decimal)dr["私帐汇款船务费"];
                    dr["百业装卸发票"] = (Decimal)dr["应收商检费合计"] + (Decimal)dr["应收报关费合计"] + (Decimal)dr["公帐汇款船务费"];
                    dr["运输发票"] = dr["应收运输费合计"];
                    dr["应收费用合计"] = (Decimal)dr["百业收据"] + (Decimal)dr["百业装卸发票"] + (Decimal)dr["运输发票"];
                    dr["应付费用"] = (Decimal)dr["应付商检费"] + (Decimal)dr["应付运输费"] + (Decimal)dr["应付报关费"]
                        + (Decimal)dr["应付单证费用合计"] + (Decimal)dr["应付其他费用合计"]
                        + (Decimal)dr["私帐汇款船务费"] + (Decimal)dr["公帐汇款船务费"];

                    //dtNew.Rows.Add(dr.ItemArray);
                    dicContractNo2DataRow.Add(ds.Tables[0].Rows[i]["工厂名称"].ToString(), dr);
                }
            }
        }

        private void ShowAllRecordInDataGridView(string strWhere)
        {
            dicContractNo2DataRow.Clear();
            DateTime dtFirst = FirstDayOfMonth(this.dateTimePickerDate.Value);
            DateTime dtEnd = LastDayOfMonth(this.dateTimePickerDate.Value);


            DataSet ds = m_bllFacFeeTab.ShowRecvFacFeeRecEx(@"BYDepartTab.DepartName = '" + this.comboBoxDep.Text + "'"
                         + " and BGDComeBackTab.SBDate >= '" + dtFirst.Date + "'"
                         + " and BGDComeBackTab.SBDate <= '" + dtEnd.Date + "'");
            if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                DataTable dtNew2 = new DataTable();

                Fee_HelpClass.MakeColumn(dtNew2);
                Fee_HelpClass.FillDataTable(dtNew2, ds, dicContractNo2DataRow);
                //MakeColumn(dtNew2);
                //FillDataTable(dtNew2, ds);





                ds = m_bllFacFeeTab.ShowMonthDepRecvMoneyInvoiceDetailRec("BGDComeBackTab.SBDate >= '" + dtFirst.Date + "'"
                                    + " and BGDComeBackTab.SBDate <= '" + dtEnd.Date + "'"
                                    + " and BYDepartTab.BYDepartTabID = '" + this.comboBoxDep.SelectedValue + "'");

                if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                {
                    ds.Tables[0].Columns.Add("编号", System.Type.GetType("System.String"));
                    ds.Tables[0].Columns["编号"].SetOrdinal(3);
                    ds.Tables[0].Columns.Add("应收费用", System.Type.GetType("System.Decimal"));
                    ds.Tables[0].Columns["应收费用"].SetOrdinal(5);
                    ds.Tables[0].Columns.Add("开票明细类别", System.Type.GetType("System.String"));
                    ds.Tables[0].Columns["开票明细类别"].SetOrdinal(6);
                    ds.Tables[0].Columns.Add("开票金额", System.Type.GetType("System.Decimal"));
                    ds.Tables[0].Columns["开票金额"].SetOrdinal(7);


                    DataTable dtNew = null;
                    dtNew = ds.Tables[0].Clone();
                    string strFacName = "";
                    Decimal dtTempTotal = 0;
                    int nTotalTemp = 0;
                    int nSeq = 0;

                    Decimal dtShouldRecvTemp = 0;

                    Decimal dtTrueKaiPiaoTemp = 0;
                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        dtTrueKaiPiaoTemp += Convert.ToDecimal(ds.Tables[0].Rows[i]["实际票面金额"].ToString());
                        string strDep = ds.Tables[0].Rows[i]["所属部门"].ToString();
                        strDep = strDep.Substring(0, 1);
                        DateTime dtSB = (DateTime)ds.Tables[0].Rows[i]["申报日期"];

                        string strYear = dtSB.Year.ToString();
                        string strMon = dtSB.Month.ToString();
                        string strFind = strDep + strYear + strMon;


                        string strTemp = ds.Tables[0].Rows[i]["合同编号"].ToString();
                        string strKaiPiaoCate = ds.Tables[0].Rows[i]["开票种类名称"].ToString();
                        string strKaiPiaoCateTemp = ds.Tables[0].Rows[i]["实际开票明细类别"].ToString();
                        if (strKaiPiaoCateTemp == "")
                            ds.Tables[0].Rows[i]["实际开票明细类别"] = strKaiPiaoCate;
                        ds.Tables[0].Rows[i]["开票明细类别"] = strKaiPiaoCate;
                        DataRow dr = dicContractNo2DataRow[strTemp];
                        if (strKaiPiaoCate.IndexOf("装卸") >= 0)
                        {
                            ds.Tables[0].Rows[i]["开票金额"] = (Decimal)dr["百业装卸发票"];
                            if ((Decimal)ds.Tables[0].Rows[i]["实际票面金额"] == 0)
                                ds.Tables[0].Rows[i]["实际票面金额"] = (Decimal)dr["百业装卸发票"];
                        }
                        else if (strKaiPiaoCate.IndexOf("运输") >= 0)
                        {
                            ds.Tables[0].Rows[i]["开票金额"] = (Decimal)dr["运输发票"];
                            if ((Decimal)ds.Tables[0].Rows[i]["实际票面金额"] == 0)
                                ds.Tables[0].Rows[i]["实际票面金额"] = (Decimal)dr["运输发票"];
                        }
                        else
                        {
                            ds.Tables[0].Rows[i]["开票金额"] = (Decimal)dr["百业收据"];
                            if ((Decimal)ds.Tables[0].Rows[i]["实际票面金额"] == 0)
                                ds.Tables[0].Rows[i]["实际票面金额"] = (Decimal)dr["百业收据"];
                        }

                        if (strFacName.CompareTo(strTemp) != 0)//切换工厂了
                        {
                            if (dtNew.Rows.Count > 0)
                            {
                                for (int j = 1; j <= nTotalTemp; j++)
                                {
                                    dtNew.Rows[dtNew.Rows.Count - j]["应收费用"] = dtTempTotal;
                                }
                                dtTempTotal = 0;
                                nTotalTemp = 0;
                            }

                            strFacName = strTemp;
                            nSeq++;
                        }

                        if ((Decimal)ds.Tables[0].Rows[i]["开票金额"] > 0)
                        {
                            ds.Tables[0].Rows[i]["编号"] = strFind + nSeq.ToString().PadLeft(4, '0');
                            dtNew.Rows.Add(ds.Tables[0].Rows[i].ItemArray);
                            nTotalTemp++;
                            dtTempTotal += (Decimal)ds.Tables[0].Rows[i]["开票金额"];
                            dtShouldRecvTemp += (Decimal)ds.Tables[0].Rows[i]["开票金额"];
                        }
                        else if ((Decimal)ds.Tables[0].Rows[i]["实际票面金额"] > 0)
                        {
                            int nId = Convert.ToInt32(ds.Tables[0].Rows[i]["FeeInvoiceTabID"].ToString(), 10);
                            DGBY.Model.FeeInvoiceTab modelFeeInvoiceTab = m_bllFeeInvoiceTab.GetModel(nId);
                            modelFeeInvoiceTab.TrueInvoiceJinE = 0;
                            m_bllFeeInvoiceTab.Update(modelFeeInvoiceTab);
                        }

                    }

                    if (dtNew.Rows.Count > 0)
                    {
                        for (int j = 1; j <= nTotalTemp; j++)
                        {
                            dtNew.Rows[dtNew.Rows.Count - j]["应收费用"] = dtTempTotal;
                        }
                        dtTempTotal = 0;
                        nTotalTemp = 0;
                    }

                    DataRow drTotal = dtNew.NewRow();
                    drTotal["编号"] = "合计";
                    drTotal["应收费用"] = dtShouldRecvTemp;
                    drTotal["开票金额"] = dtShouldRecvTemp;
                    drTotal["实际票面金额"] = dtTrueKaiPiaoTemp;
                    drTotal["工厂简称"] = "";
                    dtNew.Rows.Add(drTotal.ItemArray);

                    ultraGrid1.DataSource = dtNew;
                    ultraGrid1.DisplayLayout.Bands[0].Columns[0].Hidden = true;
                    ultraGrid1.DisplayLayout.Bands[0].Columns[1].Hidden = true;
                    ultraGrid1.DisplayLayout.Bands[0].Columns[2].Hidden = true;
                    ultraGrid1.DisplayLayout.Bands[0].Columns[12].Hidden = true;
                    ultraGrid1.DisplayLayout.Bands[0].Columns[13].Hidden = true;
                    ultraGrid1.DisplayLayout.Bands[0].Columns[14].Hidden = true;
                }
            }
          
        }
        private void buttonImport_Click(object sender, EventArgs e)
        {
            ShowAllRecordInDataGridView("");
            
        }

        private void Frm_MonthDepRecvMoneyInvoiceDetailAndReg_Load(object sender, EventArgs e)
        {
            LocalPrintPreveiw();
            InitCombox();
        }

        private void ultraGrid1_InitializeRow(object sender, Infragistics.Win.UltraWinGrid.InitializeRowEventArgs e)
        {
            ultraGrid1.DisplayLayout.Override.CellAppearance.TextHAlign = HAlign.Center;
            ultraGrid1.DisplayLayout.Override.CellAppearance.TextVAlign = VAlign.Middle;
            ultraGrid1.DisplayLayout.Override.MergedCellAppearance.TextHAlign = HAlign.Center;
            ultraGrid1.DisplayLayout.Override.MergedCellAppearance.TextVAlign = VAlign.Middle;

            ultraGrid1.DisplayLayout.Bands[0].Columns["编号"].MergedCellStyle = MergedCellStyle.Always;
            ultraGrid1.DisplayLayout.Bands[0].Columns["工厂简称"].MergedCellStyle = MergedCellStyle.Always;
            ultraGrid1.DisplayLayout.Bands[0].Columns["应收费用"].MergedCellStyle = MergedCellStyle.Always;
            ultraGrid1.DisplayLayout.Bands[0].Columns["寄件日期"].MergedCellStyle = MergedCellStyle.Always;
            ultraGrid1.DisplayLayout.Bands[0].Columns["快递号"].MergedCellStyle = MergedCellStyle.Always;
            ultraGrid1.DisplayLayout.Bands[0].Columns["编号"].MergedCellEvaluator = new
   CustomMergedCellEvaluator(this.ultraGrid1);
            ultraGrid1.DisplayLayout.Bands[0].Columns["工厂简称"].MergedCellEvaluator = new
   CustomMergedCellEvaluator(this.ultraGrid1);
            ultraGrid1.DisplayLayout.Bands[0].Columns["应收费用"].MergedCellEvaluator = new
CustomMergedCellEvaluator(this.ultraGrid1);
            ultraGrid1.DisplayLayout.Bands[0].Columns["寄件日期"].MergedCellEvaluator = new
   CustomMergedCellEvaluator(this.ultraGrid1);
            ultraGrid1.DisplayLayout.Bands[0].Columns["快递号"].MergedCellEvaluator = new
CustomMergedCellEvaluator(this.ultraGrid1);

        }

        private void ultraGrid1_AfterCellActivate(object sender, EventArgs e)
        {
            string strTemp = this.ultraGrid1.Rows[this.ultraGrid1.ActiveCell.Row.Index].Cells[2].Text;
            if (strTemp == "合计")
                return;
            string strFeeTTLoanTabID = this.ultraGrid1.Rows[this.ultraGrid1.ActiveCell.Row.Index].Cells[1].Text;
            m_nSelectFeeTTLoanTabID = Convert.ToInt32(strFeeTTLoanTabID, 10);

            this.textBoxFacMame.Text = this.ultraGrid1.Rows[this.ultraGrid1.ActiveCell.Row.Index].Cells["工厂简称"].Text;
            this.textBoxRecvFee.Text = this.ultraGrid1.Rows[this.ultraGrid1.ActiveCell.Row.Index].Cells["应收费用"].Text;
            this.textBoxKaiPiaoDetail.Text = this.ultraGrid1.Rows[this.ultraGrid1.ActiveCell.Row.Index].Cells["开票明细类别"].Text;
            this.textBoxKPJinE.Text = this.ultraGrid1.Rows[this.ultraGrid1.ActiveCell.Row.Index].Cells["开票金额"].Text;
            this.textBoxTrueKPDetail.Text = this.ultraGrid1.Rows[this.ultraGrid1.ActiveCell.Row.Index].Cells["实际开票明细类别"].Text;
            this.textBoxInvoiceNo.Text = this.ultraGrid1.Rows[this.ultraGrid1.ActiveCell.Row.Index].Cells["发票号码"].Text;
            this.textBoxTrueKPJinE.Text = this.ultraGrid1.Rows[this.ultraGrid1.ActiveCell.Row.Index].Cells["实际票面金额"].Text;
            this.textBoxExpressNo.Text = this.ultraGrid1.Rows[this.ultraGrid1.ActiveCell.Row.Index].Cells["快递号"].Text;
            DGBY.Model.FeeInvoiceTab modelFeeInvoiceTab = m_bllFeeInvoiceTab.GetModel(m_nSelectFeeTTLoanTabID);
            if (modelFeeInvoiceTab != null)
            {
                this.dateTimePickerPostDate.Value = (DateTime)modelFeeInvoiceTab.PostDate;

            }
        }


        private void buttonModify_Click(object sender, EventArgs e)
        {
            try
            {
                if (ClassInputValid.IsDecimal(this.errorProvider1, this.textBoxTrueKPJinE))
                    return;

                DGBY.Model.FeeInvoiceTab modelFeeInvoiceTab = m_bllFeeInvoiceTab.GetModel(m_nSelectFeeTTLoanTabID);
                if (modelFeeInvoiceTab == null)
                {
                    MessageBox.Show("数据库不存在该记录!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                modelFeeInvoiceTab.TrueInvoiceJinE = Convert.ToDecimal(this.textBoxTrueKPJinE.Text);
                modelFeeInvoiceTab.FeeInvoiceName = this.textBoxTrueKPDetail.Text;
                DateTime dtFirst = FirstDayOfMonth(this.dateTimePickerDate.Value);
                DateTime dtEnd = LastDayOfMonth(this.dateTimePickerDate.Value);
                modelFeeInvoiceTab.ExpressNo = this.textBoxExpressNo.Text;
                modelFeeInvoiceTab.PostDate = this.dateTimePickerPostDate.Value;
                m_bllFeeInvoiceTab.Update(modelFeeInvoiceTab);
                DataSet ds = m_bllFacFeeTab.ShowMonthDepRecvMoneyInvoiceDetailRec("FactoryDataTab.FactoryNameJX = '" + this.textBoxFacMame.Text + "'"
                        + " and BGDComeBackTab.SBDate >= '" + dtFirst.Date + "'"
                        + " and BGDComeBackTab.SBDate <= '" + dtEnd.Date + "'"
                        + " and BYDepartTab.BYDepartTabID = '" + this.comboBoxDep.SelectedValue + "'");

                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    int nId = Convert.ToInt32(ds.Tables[0].Rows[i]["FeeInvoiceTabID"].ToString(), 10);
                    if (nId == m_nSelectFeeTTLoanTabID)
                        continue;
                    DGBY.Model.FeeInvoiceTab modelFeeInvoiceTabTemp = m_bllFeeInvoiceTab.GetModel(nId);
                    modelFeeInvoiceTabTemp.ExpressNo = this.textBoxExpressNo.Text;
                    modelFeeInvoiceTabTemp.PostDate = this.dateTimePickerPostDate.Value;
                    m_bllFeeInvoiceTab.Update(modelFeeInvoiceTabTemp);
                }


                ShowAllRecordInDataGridView("");
                MessageBox.Show("数据修改成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.ToString(), "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

            }
           
        }

        private void buttonExportToExcel_Click(object sender, EventArgs e)
        {
            DataTable dt = (DataTable)ultraGrid1.DataSource;

            if (dt != null)
            {
                if (dt.Rows.Count > 0)
                {
                    SaveFileDialog sfd = new SaveFileDialog();
                    sfd.Filter = "Excel文件(*.xls)|*.xls";
                    string outFile = "";

                    if (sfd.ShowDialog() == DialogResult.OK)
                    {
                        outFile = sfd.FileName;
                    }
                    else
                    {
                        return;
                    }

                    ultraGridExcelExporter1.Export(ultraGrid1, outFile);
                }
            }
        }

        private void buttonPrint_Click(object sender, EventArgs e)
        {
            this.ultraGridPrintDocument1.Grid = this.ultraGrid1;
            this.ultraPrintPreviewDialog1.Document = this.ultraGridPrintDocument1;
            this.ultraPrintPreviewDialog1.ShowDialog(this);
        }
        private void ultraGridExcelExporter1_CellExported(object sender, Infragistics.Win.UltraWinGrid.ExcelExport.CellExportedEventArgs e)
        {
            // Get the cell being exporter
            UltraGridCell cell = e.GridRow.Cells[e.GridColumn];

            // Get the Merged cells. 
            UltraGridCell[] mergedCells = cell.GetMergedCells();


            // Check to see if there are any merged cells. If not, we don't need to do anything. 
            if (mergedCells != null)
            {
                // There are merged cells. Check to see if the cell being exported is the first one. 
                bool isFirstCell = true;
                foreach (UltraGridCell mergedCell in mergedCells)
                {
                    if (cell.Row.Index > mergedCell.Row.Index)
                    {
                        // If the cell being exported has a higher index that any of the cells
                        // it is merged with, them it's not the first cell and we should already
                        // have handled the merge. 
                        isFirstCell = false;
                        break;
                    }
                }

                // If it is the first cell, merge this cell with the cells below it based on the 
                // count of the merged cells. 
                if (isFirstCell)
                {
                    int rowIndex = e.CurrentRowIndex;
                    int colIndex = e.CurrentColumnIndex;
                    Infragistics.Excel.WorksheetMergedCellsRegion mergedRegion = e.CurrentWorksheet.MergedCellsRegions.Add(
                        rowIndex,
                        colIndex,
                        rowIndex + (mergedCells.Length - 1),
                        colIndex);
                    mergedRegion.CellFormat.Alignment = Infragistics.Excel.HorizontalCellAlignment.Center;
                    mergedRegion.CellFormat.VerticalAlignment = Infragistics.Excel.VerticalCellAlignment.Center;
                }

            }
        }
    }
}
